﻿using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using WeatherSystem.Net;
using WeatherSystem.Data;

namespace WeatherSystem.Application.Index
{
    class Index : IApplication
    {
        public string Name => "";
        public static bool Signature = false;
        private readonly string token = "whuttokenaz1807";
        public HttpResponseArgs Handle(HttpArgs args)
        {
            if (Signature)
            {
                var signature = args.GetArgValue("signature");
                var echostr = args.GetArgValue("echostr");
                var timestamp = args.GetArgValue("timestamp");
                var nonce = args.GetArgValue("nonce");
                var dic = new Dictionary<string, string>();
                dic.Add("token", token);
                dic.Add("timestamp", timestamp);
                dic.Add("nonce", nonce);
                var dicSort = from obj in dic orderby obj.Value ascending select obj;
                string ttn = "";
                foreach (var kv in dicSort)
                {
                    ttn += kv.Value;
                }
                if (SHA.VerifySha1Hash(ttn, signature))
                {
                    return new HttpResponseArgs(echostr);
                }
            }
            if (!args.GetPostValue().ContainsKey("MsgType")) return null;
            var msgType = args.GetPostValue()["MsgType"]["#cdata-section"].ToString();
            MsgHandler.IMsgHandler handler;
            switch (msgType)
            {
                case "text":
                    handler = new MsgHandler.TextHandler();
                    break;
                case "image":
                    handler = new MsgHandler.ImageHandler();
                    break;
                case "voice":
                    handler = new MsgHandler.VoiceHandler();
                    break;
                case "event":
                    handler = new MsgHandler.EventHandler();
                    break;
                case "shortvideo":
                    handler = new MsgHandler.ShortVidioHandler();
                    break;
                case "location":
                    handler = new MsgHandler.LocationHandler();
                    break;
                case "link":
                    handler = new MsgHandler.LinkHandler();
                    break;
                case "vidio":
                    
                default:
                    return null;
            }
            var msg = handler.Handle(args);
            var response = ContentAdapter.ContentManager.GetResponseContent(msg);
            var responseJobject = response.GetJobject();
            return new HttpResponseArgs(responseJobject, ResponseType.Xml);
        }
    }
}
